# ------------------------------------------------------------------------------------------------
### Generate Figure 6: Map of 2019 PiS vote share
# ------------------------------------------------------------------------------------------------

# Load data
load("../data/processed/LGBTQ_election_data.Rda")

# Define color scheme for PiS vote share bins
bin_colors <- c("#FAEFEF", "#F5DBDC", "#EAB5B6", "#D9534F", "#8C0D10")

# Load and process municipality boundaries
PL_gmina <- gisco_get_lau(country = "PL", year="2020") %>%
  mutate(id = paste0(substr(LAU_ID, 5, 6), substr(LAU_ID, 10, nchar(LAU_ID)))) %>%
  left_join(
    LGBTQ_election_data %>% 
      select(id, any_level_any_type) %>% 
      unique(), 
    by = "id"
  ) 

# Unite polygons within treated and control municipalities
united_treated <- PL_gmina %>% 
  filter(any_level_any_type == 1) %>%
  st_make_valid() %>%
  st_union()

united_control <- PL_gmina %>% 
  filter(any_level_any_type == 0) %>%
  st_make_valid() %>%
  st_union()

# Convert united polygons into MultiLineStrings and create policy adoption boundary
boundary_treated <- st_boundary(united_treated)
boundary_control <- st_boundary(united_control)
cutoff <- st_intersection(boundary_treated, boundary_control)

# Get PiS vote share for 2019
elec19 <- LGBTQ_election_data %>%
  filter(eyear == 2019) %>%
  group_by(id) %>%
  summarise(pis19 = sum(pis[eyear == 2019])) 

# Join election data and create vote share bins
PL_gmina <- PL_gmina %>%
  left_join(elec19, by = "id") %>%
  mutate(
    pis19_bins = cut(pis19, 
                      breaks = c(-Inf, 20, 40, 60, 80, Inf), 
                      labels = c("0-20", "20-40", "40-60", "60-80", "80+"),
                      include.lowest = TRUE)
  )

# Generate map
ggplot(PL_gmina) +
  geom_sf(aes(fill = pis19_bins)) +
  geom_sf(data = cutoff, fill = NA, color = "black") +
  scale_fill_manual(
    values = bin_colors,
    name = "PiS vote share (%)",
    guide = guide_legend(title.position = "top", title.hjust = 0.5)
  ) +
  theme_map() +
  theme(
    legend.position = "bottom",
    legend.justification = 0.5,
    text = element_text(size = 23)
  )

# Save the plot
ggsave("../output/plots/figure6.pdf", width = 14, height = 10, dpi = 700)

